package com.jia.lidao.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.jia.lidao.App;
import com.jia.lidao.Constans;
import com.jia.lidao.R;
import com.jia.lidao.enity.UserInfor;
import com.jia.lidao.enity.UserWX;
import com.jia.lidao.enity.WXAccessToken;
import com.jia.lidao.others.API;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import okhttp3.Call;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	private IWXAPI api;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //  setContentView(R.layout.entry);
		api = App.api;
		api.handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
    	Log.e("HQQ","onReq ");
		switch (req.getType()) {
		case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
			break;
		case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
			goToShowMsg((ShowMessageFromWX.Req) req);
			break;
		default:
			break;
		}
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.e("HQQ","BaseResp ");
		int result = 0;
		
		Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();
		
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			result = R.string.errcode_success;
			if(resp instanceof SendAuth.Resp){
				SendAuth.Resp newResp = (SendAuth.Resp) resp;
				String code = newResp.code;
				Log.e("HQQ","onResp code = "+code);
				String url =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constans.APP_ID
						+"&secret="+ Constans.APPSECRET +"&code="+code+"&grant_type=authorization_code";
				TypeToken<WXAccessToken> typeToken = new TypeToken<WXAccessToken>(){};
				OkHttpUtils.get().url(url).build().execute(new ObjectCallBack<WXAccessToken>(typeToken) {
					@Override
					public void onError(Call call, Exception e, int id) {

					}

					@Override
					public void onResponse(WXAccessToken response, int id) {
							Log.e("HQQ","response:  "+response.getAccess_token());
						getUserInfo(response.getAccess_token(),response.getOpenid());
					}
				});
			}
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = R.string.errcode_cancel;
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = R.string.errcode_deny;
			break;
		case BaseResp.ErrCode.ERR_UNSUPPORT:
			result = R.string.errcode_unsupported;
			break;
		default:
			result = R.string.errcode_unknown;
			break;
		}
		
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
		if(resp.errCode != BaseResp.ErrCode.ERR_OK){
			finish();
		}
	}
	

	
	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
		StringBuffer msg = new StringBuffer();
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);
		Toast.makeText(this, msg.toString(), Toast.LENGTH_LONG).show();
	}

	////获取到token和openID之后，调用此接口得到身份信息
	private void getUserInfo(String token, String openID) {
		final String url = "https://api.weixin.qq.com/sns/userinfo?" + "access_token=" + token + "&openid=" + openID + "&lang=zh_CN";
		TypeToken<UserWX> typeToken = new TypeToken<UserWX>(){};

		OkHttpUtils.get().url(url).build().execute(new ObjectCallBack<UserWX>(typeToken) {
			@Override
			public void onError(Call call, Exception e, int id) {

			}

			@Override
			public void onResponse(final UserWX responsewx, int id) {
				if(null != responsewx){
						Log.e("HQQ"," responsewx :"+responsewx.getNickname());
					String url = API.LOGIN_OAUTH+"oauth_id="+responsewx.getUnionid()+"&open_id="+responsewx.getOpenid()
							+"&platform=2"+"&avatar="+responsewx.getHeadimgurl()+"&nickname="+responsewx.getNickname();
					HashMap<String,String> headers = new HashMap<>();
					headers.put("Accept","*/*");

					TypeToken<UserInfor> typeToken = new TypeToken<UserInfor>(){};
					OkHttpUtils.post().url(url).headers(headers).build().execute(new ObjectCallBack<UserInfor>(typeToken) {
						@Override
						public void onError(Call call, Exception e, int id) {

						}

						@Override
						public void onResponse(UserInfor response, int id) {
							if(null != response){
								if(response.getErr_code() == 0){
//									EventBus.getDefault().post(response.getAuthorization());
//									UserInfoUtil.saveToken(WXEntryActivity.this,response.getAuthorization().getAccess_token());
//									Intent inten = new Intent(WXEntryActivity.this, MainActivity.class);
//									startActivity(inten);
//									finish();
								}
							}

						}
					});
				}
			}
		});
	}
}